//
//  ViewController.swift
//  5.4.Attaching Multiple Dynamic items to Each Other
//
//  Created by joker on 15/7/31.
//  Copyright (c) 2015年 joker. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    var squareView: UIView?
    var squareViewAnchorView: UIView?
    var anchorView: UIView?
    var animator: UIDynamicAnimator?
    var attachmentBehavior: UIAttachmentBehavior?
    
    func createSmallSquareView(){
        squareView = UIView(frame: CGRect(x: 0, y: 0, width: 80, height: 80))
        if let theSquareView = squareView {
            theSquareView.backgroundColor = UIColor.greenColor()
            theSquareView.center = view.center
            
            squareViewAnchorView = UIView(frame: CGRect(x: 60, y: 0, width: 20, height: 20))
            squareViewAnchorView?.backgroundColor = UIColor.brownColor()
            theSquareView.addSubview(squareViewAnchorView!)
            view.addSubview(theSquareView)
        }
    }
    func createAnchorView() {
        anchorView = UIView(frame: CGRect(x: 120, y: 120, width: 20, height: 20))
        anchorView?.backgroundColor = UIColor.redColor()
        view.addSubview(anchorView!)
    }
    
    func createGestureRecognizer() {
        let panGestureRecoginzer = UIPanGestureRecognizer(target: self, action: "handlePan:")
        view.addGestureRecognizer(panGestureRecoginzer)
    }
    func createAnimatorAndBehaviors() {
        animator = UIDynamicAnimator(referenceView: view)
        
        let collision = UICollisionBehavior(items: [squareView!])
        collision.translatesReferenceBoundsIntoBoundary = true
        
        attachmentBehavior = UIAttachmentBehavior(item: squareView!, offsetFromCenter: UIOffset(horizontal: 30, vertical: -40), attachedToAnchor: anchorView!.center)
        
        animator?.addBehavior(collision)
        animator?.addBehavior(attachmentBehavior)
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        createGestureRecognizer()
        createSmallSquareView()
        createAnchorView()
        createAnimatorAndBehaviors()
    }
    
    func handlePan(pan: UIPanGestureRecognizer) {
        let tapPoint = pan.locationInView(view)
        attachmentBehavior?.anchorPoint = tapPoint
        anchorView?.center = tapPoint
    }
}

